package expansion.sort;

import java.util.Arrays;

public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {3,1,8,2,4,7,0,5,6};
        System.out.println(Arrays.toString(arr));
        int[] temp = new int[arr.length];
        sort(arr,0,arr.length-1,temp);
        System.out.println(Arrays.toString(arr));
    }

    static void sort(int[] arr, int left, int right, int[] temp) {
        if (left >= right){
            return;
        }
        int mid = (left+right)/2;
        sort(arr, left, mid, temp);
        sort(arr,mid+1,right,temp);
        mergeSort(arr, left, mid, right, temp);
    }

    private static void mergeSort(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left;
        int j = mid+1;
        int k = left;
        while (i <= mid && j <= right){
            if(arr[i]>=arr[j]){
                temp[k] = arr[j];
                j++;
            }else {
                temp[k] = arr[i];
                i++;

            }
            k++;
        }
        if (i<=mid){
            System.arraycopy(arr,i,temp,k,mid-i+1);
        }else {
            System.arraycopy(arr,j,temp,k,right-j+1);
        }
        System.arraycopy(temp,left,arr,left,right-left+1);
    }

}
